/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.semester.service.impl;

import com.fanrenqiji.entity.ParentEntity;
import com.fanrenqiji.modules.business.parent.dao.ParentDao;
import com.fanrenqiji.modules.business.semester.vo.SemesterPageVO;
import com.fanrenqiji.modules.business.wechatuser.dao.WeChatUserDao;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.bean.WxMpMassOpenIdsMessage;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;

import com.fanrenqiji.entity.SemesterEntity;
import com.fanrenqiji.modules.business.semester.vo.SemesterVO;
import com.fanrenqiji.modules.business.semester.dao.SemesterDao;
import com.fanrenqiji.modules.business.semester.service.SemesterService;

import org.dozer.DozerBeanMapper;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.fanrenqiji.common.persistence.Page;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;
import org.apache.commons.lang3.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 学期信息业务逻辑实现
 *
 * @author wentao
 */
@Service(value = "semester")
@Transactional(readOnly = true)
public class SemesterServiceImpl implements SemesterService {

    @Autowired
    private SemesterDao semesterDao;
    @Autowired
    private WeChatUserDao weChatUserDao;
    @Autowired
    private ParentDao parentDao;

    @Autowired
    DozerBeanMapper beanMapper;

    /**
     * 插入
     *
     * @param semester 插入的对象
     * @return 插入数据条数
     */
    @Transactional
    public SemesterVO insert(SemesterVO semester) {
        SemesterEntity semesterEntity = new SemesterEntity();
        beanMapper.map(semester, semesterEntity);
        semesterDao.save(semesterEntity);
        beanMapper.map(semesterEntity, semester);
        return semester;
    }


    /**
     * 批量插入
     *
     * @param list 数据列表
     * @return 插入数据条数
     */
    @Transactional
    public void insertList(List<SemesterVO> list) {
        for (SemesterVO semester : list) {
            insert(semester);
        }
    }


    /**
     * 修改
     *
     * @param semester 修改的数据
     * @return 修改的数据
     */
    @Transactional
    public SemesterVO update(SemesterVO semester) {
        SemesterEntity semesterEntity = null;
        if (StringUtils.isNotEmpty(semester.getId())) {
            semesterEntity = semesterDao.findOne(Long.parseLong(semester.getId()));
        }
        if (semesterEntity == null) {
            semesterEntity = new SemesterEntity();
        }
        beanMapper.map(semester, semesterEntity);
        semesterDao.save(semesterEntity);

        if (semesterEntity.getEnroll() == 1 && semesterEntity.getFormal() == 1) {
            try {
                semesterDao.updateBySql("update tb_semester set enroll = 0 where enroll=1 and formal=1 and id !=" + semesterEntity.getId());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        beanMapper.map(semesterEntity, semester);
        return semester;
    }


    /**
     * 删除
     *
     * @param id 数据标识
     * @return 删除的数据条数
     */
    @Transactional
    public void delete(String id) {
        semesterDao.deleteById(Long.parseLong(id));
    }


    /**
     * 查询所有数据
     *
     * @return 数据列表
     */
    public List<SemesterVO> getAll() {
        List<SemesterVO> list = Lists.newArrayList();
        List<SemesterEntity> entities = semesterDao.findAllList();
        for (SemesterEntity semesterEntity : entities) {
            SemesterVO semesterVO = new SemesterVO();
            beanMapper.map(semesterEntity, semesterVO);
            list.add(semesterVO);
        }
        return list;
    }


    /**
     * 通过条件查询数据列表
     *
     * @param semester 查询条件
     * @return 数据列表
     */
    public List<SemesterVO> getList(SemesterVO semester) {
        List<SemesterVO> list = Lists.newArrayList();
        DetachedCriteria dc = semesterDao.createDetachedCriteria();
        dc.add(Restrictions.eq(SemesterEntity.DEL_FLAG, SemesterEntity.DEL_FLAG_NORMAL));
    /*
    dc.createAlias("semester", "semester"); // as

    dc.add(Restrictions.ne("id", 1L)); // !=

    if (StringUtils.isNotEmpty(semester.getName())) {
        dc.add(Restrictions.like("name", "%" + semester.getName() + "%")); //like
    }
    if (StringUtils.isNotEmpty(semester.getName())) {
        dc.add(Restrictions.eq("name", semester.getName())); //=
    }

	dc.addOrder(Order.asc("office.id")).addOrder(Order.asc("name"));  //排序

    */
        List<SemesterEntity> entities = semesterDao.find(dc);
        for (SemesterEntity semesterEntity : entities) {
            SemesterVO semesterVO = new SemesterVO();
            beanMapper.map(semesterEntity, semesterVO);
            list.add(semesterVO);
        }
        return list;
    }


    /**
     * 通过id查询数据
     *
     * @param id 数据标识
     * @return 数据对象
     */
    public SemesterVO get(String id) {
        SemesterVO semester = new SemesterVO();
        SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(id));
        if (semesterEntity == null) {
            semesterEntity = new SemesterEntity();
        }
        beanMapper.map(semesterEntity, semester);
        return semester;
    }


    /**
     * 根据条件分页查询
     *
     * @param page
     * @param semester
     * @return
     */
    public Page<SemesterVO> findSemesterByPage(Page<SemesterVO> page, SemesterVO semester) {
        Page<SemesterEntity> pageEntity = new Page<SemesterEntity>(page.getPageNo(), page.getPageSize());
        DetachedCriteria dc = semesterDao.createDetachedCriteria();
        dc.add(Restrictions.eq(SemesterEntity.DEL_FLAG, SemesterEntity.DEL_FLAG_NORMAL));

        if (!StringUtils.isNotEmpty(page.getOrderBy())) {
            dc.addOrder(Order.desc("id"));
        }
        pageEntity = semesterDao.find(pageEntity, dc);
        beanMapper.map(pageEntity, page);
        List<SemesterVO> list = Lists.newArrayList();
        for (SemesterEntity semesterEntity : pageEntity.getList()) {
            SemesterVO semesterVO = new SemesterVO();
            beanMapper.map(semesterEntity, semesterVO);
            list.add(semesterVO);
        }
        page.setList(list);
        return page;
    }

    @Transactional
    public void begin(SemesterVO semesterVO) {

        Calendar c = Calendar.getInstance();
        int i = c.get(Calendar.WEEK_OF_YEAR);//第几周
        int year = c.get(Calendar.YEAR);
        i += 1;
        String d = year + "" + i;
        DetachedCriteria dc = semesterDao.createDetachedCriteria();
        dc.add(Restrictions.eq("number", d));
        List<SemesterEntity> semesterEntities = semesterDao.find(dc);
        if (semesterEntities.isEmpty()) {
            SemesterEntity semesterEntity = new SemesterEntity();
            semesterEntity.setNumber(d);
            semesterDao.save(semesterEntity);
        }

        SemesterEntity semesterEntity = semesterDao.findOne(Long.parseLong(semesterVO.getId()));
        List<ParentEntity> parentEntities = semesterEntity.getParentEntities();
        ArrayList<String> opids = Lists.newArrayList();
        for (ParentEntity parentEntity : parentEntities) {
            String openId = parentEntity.getWeChatUser().getOpenId();
            opids.add(openId);
        }

        // 接下来就是发送消息
        String url = "http://u15276z866.iask.in/message/getMessage";
       /* WxMpMassOpenIdsMessage massMessage = new WxMpMassOpenIdsMessage();
        WxMpKefuMessage.WxArticle article1 = new WxMpKefuMessage.WxArticle();
        article1.setDescription("点击前往注册页面注册，哈哈哈");
        article1.setTitle("点击注册");
        article1.setUrl(fanrenqijidomain+"/user/toregister?openId=" + wxMessage.getFromUser()+"&headImgUrl="+wxMpUser.getHeadImgUrl());
        WxMpKefuMessage message = WxMpKefuMessage
                .NEWS()
                .toUser(wxMessage.getFromUser())
                .addArticle(article1)
                .build();
        try {
                wxService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException e) {
                e.printStackTrace();
        }*/

    }

}
